package sseGameApps.controller.mdkbr.confirm;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;

import sseGameApps.model.mdkbr.MdKbrUser;
import sseGameApps.service.mdkbr.MdKbrUserService;

public class DecideController extends Controller {

    private MdKbrUserService service = new MdKbrUserService();

    @Override
    public Navigation run() throws Exception {
        if (!validate()) {
            return forward(basePath);
        }

        MdKbrUser mdKbrUser = service.getMdKbrUser(asString("userId"));

        if(mdKbrUser != null){

            if(service.checkNoSamePlayer(asString("playerName"))){
                mdKbrUser.setPlayerName(asString("playerName"));
                service.putMdKbrUser(mdKbrUser);
                return redirect("/mdkbr/main/?userId=" + asString("userId") + "&firstLogin=1");

            } else {
              requestScope("playerName", asString("playerName"));
              Validators v = new Validators(request);
              v.getErrors().put("playerName", "この選手名は登録済です");
              return forward(basePath);
            }

        } else {
            return redirect("/mdkbr/");
        }
    }

    protected boolean validate() {
        Validators v = new Validators(request);
        v.add("playerName", v.required());
        return v.validate();
    }
}
